import { CellType } from ".";
import { dom } from "../tool";


// 文本输入框
function Textarea(this: CellType, attribute: any = {}, mode = 3, template: any) {
    const me = this;
    this.type = 2;
    attribute.type = 2;
    this.attrData = attribute;
    this.parentContainer = template;
    const { placeholder = '', defaultValue = '', disabled = false, readonly = false, fieldName } = attribute;
    const container = dom('div', {
        className: 'gkh_text_div',
        innerText: mode === 3 ? defaultValue : '',
    });
    let content: any;
    let input: any;
    let value = defaultValue;
    let height;
    let preHeight;
    function change() {
        preHeight = container.offsetHeight;
        if ((mode == 2 || mode == 4) && value !== input.value) {
            value = input.value;
            content.innerText = value;
            height = container.offsetHeight - preHeight;
            if (height && template && template.cellHeightChange) {
                template.cellHeightChange(container, height - preHeight);
            }
        }
    }
    if (mode == 2 || mode == 4) {
        content = dom('div', {
            target: container,
            className: 'gkh-text-height-adujst'
        });
        input = dom('textarea', {
            target: container,
            innerText: defaultValue,
            // attribute: { placeholder, disabled, readonly }
        });
        input.onkeyup = change;
        input.onchange = change;
    }
    this.setDisabled = (arg) => {
        input.disabled = arg;
    };
    this.setVisible = (arg) => {
        let visibility = 'string' === typeof arg ? arg : 'hidden';
        if (arg) {
            visibility = 'visible';
        }
        container.style.visibility = visibility;
    };
    this.setReadonly = (arg) => { };
    this.getValue = () => value;
    this.setValue = (arg) => {
        if (mode == 2 || mode == 4) {
            input.value = arg;
            change();
        } else {
            container.innerText = arg;
        }
    };
    this.reset = () => { this.setValue?.(defaultValue) };
    this.getAttrData = function () {
        return this.attrData;
    }
    const fieldNameChange = (arg: any) => {
        this.attrData.fieldName = arg.target.value;
    }
    this.render = () => {
        if (mode == 1) {
            dom('div', {
                target: container,
                className: 'gkh-fieldname-div',
                childs: [
                    dom('label', { innerText: '字段名：' }),
                    dom('input', {
                        attribute: { value: fieldName ? fieldName : '' },
                        listeners: { change: fieldNameChange },
                    })
                ]
            })
        }
        return container;
    };
    this.renderAfter = () => {
        change();
    }
}

export default Textarea as unknown as CellType;